const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });
const db = cloud.database()
const _ = db.command
const $ = db.command.aggregate

exports.main = async (event, context) => {
  const doc = event.data.doc;
  let remark = '';
  if (event.data.dataType == 'insert') {
    remark = '生成卡券'
  } else if (event.data.dataType == 'update') {
    switch (doc.order_state) {
      case 1:
        remark = '卡券已核销';
        break;
      case 2:
        remark = '卡券已退款';
        break;
      case 3:
        remark = '卡券已过期';
        break;
    }
  }
  await db.collection('tb_coupon_change').add({
    data: {
      modified_state: doc.coupon_state,
      modified_time: new Date().getTime(),
      coupon_id: doc._id,
      remark: remark,
    }
  })
}